package com.kbtd.interceptor;

import com.kbtd.dto.UserDTO;
import com.kbtd.utils.UserHolder;
import com.kbtd.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.kbtd.constant.RedisConstants.UV_KEY;

/**
 * UV统计拦截器
 *
 * @author wp
 * @data 2024/9/21
 */

@Component
public class UVInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserDTO user = UserHolder.getUser();
        if (!ObjectUtils.isEmpty(user)) {
            String uvKey = RedisUtils.createKey("", UV_KEY);
            stringRedisTemplate.opsForHyperLogLog().add(uvKey, user.getId().toString());
        }
        return true;
    }
}
